﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;

namespace Cloak.Mvp
{
	/// <summary>
	/// Refers by type to a presenter which can be bound to a view
	/// </summary>
	public class PresenterReference : IPresenterReference
	{
		/// <summary>
		/// Initializes a reference to the specified type
		/// </summary>
		/// <param name="type">The type of presenter bound to the view</param>
		public PresenterReference(Type type)
		{
			Contract.Requires(type != null);

			Type = type;
		}

		#region IPresenterReference
		/// <summary>
		/// Creates a presenter in the specified context
		/// </summary>
		/// <param name="context">The context in which the presenter is created</param>
		/// <param name="view">The view bound to the presenter</param>
		/// <returns>The presenter instance</returns>
		public object CreateIn(IPresenterContext context, object view)
		{
			return context.CreatePresenter(GetSite(view));
		}
		#endregion

		/// <summary>
		/// Gets the type of presenter bound to the view
		/// </summary>
		public Type Type { get; private set; }

		/// <summary>
		/// Gets the site at which the view is bound to the presenter
		/// </summary>
		/// <param name="view">The view to which the presenter is bound</param>
		/// <returns>The site at which the view is bound to the presenter</returns>
		protected virtual PresenterSite GetSite(object view)
		{
			Contract.Ensures(Contract.Result<PresenterSite>() != null);

			return new PresenterSite(Type, view);
		}
	}
}